<?php

namespace Home\Controller;

class GoodsController extends BaseMallController
{

    function _initialize()
    {
        parent::_initialize();
        $this->_user_id = session('visitor.user_id');
    }

    /**
     * @api {get} /index.php?m=Home&c=Goods&a=info 获取产品的所有信息
     */
    function info()
    {
        if(I('request.barcode')){
            $res = M('goods_spec')->where(array('barcode' => I('request.barcode')))->find();
            if(!$res){
                render('10001', '商品不存在');
            }
            $id = $res['goods_id'];
        }else if(I('request.random_str')){
            $id = get_decrypt(I('request.random_str'));
        }else if('request.id'){
            $id = I('request.id');
            if (empty($id)) {
                render('10001', '缺少参数');
            }
        }
        /* 商品信息 */
        $goods = D('goods')->get_info($id);
        $goods['description'] = str_replace("./data", C('SITE_URL') . '/data', $goods['description']);
        if(!$_POST['user_id']){
            $goods['collectAndWish'] = false;
        }else{
            $condc['item_id'] = $id;
            $condc['user_id'] = $_POST['user_id'];
            $collect = M('collect')->where($condc)->find();
            $condw['goods_id'] = $id;
            $condw['user_id'] = $_POST['user_id'];
            $wish = M('wish')->where($condw)->find();
            if($collect || $wish){
                $goods['collectAndWish'] = true;
            }else{
                $goods['collectAndWish'] = false;
            }
        }
        $goods['share_str'] = $goods['goods_name'].'￥'.set_encrypt($id).'￥';
        if (!$goods || $goods['if_show'] == 0 || $goods['closed'] == 1 || $goods['state'] != 1) {
            render('10300', '此商品不存在');
        }
        $goods['tags'] = $goods['tags'] ? explode(',', trim($goods['tags'], ',')) : array();

        /* 打折促销相关信息 BEGIN */
        $Promotion_mod = M('promotion');
        $promotion = $Promotion_mod->where("start_time<=" . time() . " AND end_time>=" . time() . " AND goods_id=" . $goods['goods_id'])->find();
        if ($promotion) {
            $i = $is_pro = 0;
            foreach ($goods['_specs'] as $spec) {
                $spec_price = unserialize($promotion['spec_price']);
                if (isset($spec_price[$spec['spec_id']]['pro_type'])) {
                    if ($spec_price[$spec['spec_id']]['pro_type'] == 'price') {
                        if ($spec['price'] > $spec_price[$spec['spec_id']]['price']) {
                            $pro_price = round($spec['price'] - $spec_price[$spec['spec_id']]['price'], 2);
                            $is_pro = 1;
                        } else {
                            $pro_price = NULL; // 考虑设置了促销后，再给该商品添加规格的情况，那么一律给新增的规格设置促销价为NULL
                            $is_pro = 0;
                        }
                    } else {
                        $pro_price = round($spec['price'] * $spec_price[$spec['spec_id']]['price'] / 10, 2);
                        $is_pro = 1;
                    }
                } else {
                    $pro_price = NULL; // 考虑设置了促销后，再给该商品添加规格的情况，那么一律给新增的规格设置促销价为NULL
                    $is_pro = 0;
                }
                $goods['_specs'][$i++] += array('pro_price' => $pro_price, 'is_pro' => $is_pro);
            }

            $goods['lefttime'] = $this->lefttime($promotion['end_time']);

            $goods += $promotion;
        }
        /* 打折促销相关信息 END */

        $data['goods'] = $goods;
        /* 店铺信息 */
        if (!$goods['store_id']) {
            render('10302', '商品中未包含店铺ID');
        }
        $data['store'] = D('store')->get_info($goods['store_id']);

        //显示产品会员等级价格
        if ($data['goods']['if_open'] && $this->_user_id) {
            $member = D('member')->get_grade_info($this->_user_id);
            $data['goods']['grade_name'] = $member['grade_name'];
            $discount = D('gradegoods')->get_user_discount($this->_user_id, $id);
            foreach ($data['goods']['_specs'] as $key => $val) {
                $data['goods']['_specs'][$key]['member_price'] = $val['price'] * $discount;
                $data['goods']['_specs'][$key]['discount'] = $discount;
            }
        } else {

            $data['goods']['if_open'] = 0;
        }

        /* 商品的自由搭配 */
        $mix_mod = M('Mix');
        $mix_list = D('Mix')->relation(true)->alias('mix')->join('LEFT JOIN ' . C('DB_PREFIX') . 'mix_goods mix_goods ON mix_goods.mix_id=mix.mix_id ')->where('nav_goods_id=' . $data['goods']['goods_id'])->order('mix.mix_id asc,mix_goods.sort_order asc')->find();
        if ($mix_list) {
            $mix_items = array();
            //自由搭配分类
            $mix_cates = array();
            foreach ($mix_list['Goods'] as $key => $val) {
                //获取最优价格
                $spec_info = M('goods_spec')
                    ->field('g.store_id, g.if_open, g.goods_id, g.goods_name, g.spec_name_1, g.spec_name_2, g.spec_name_3, g.spec_name_4, g.default_image, gs.spec_id, gs.spec_1, gs.spec_2, gs.spec_3, gs.spec_4, gs.stock, gs.price')
                    ->alias('gs')
                    ->join('LEFT JOIN ' . C('DB_PREFIX') . 'goods g ON g.goods_id = gs.goods_id')
                    ->where('spec_id=' . $val['default_spec'])
                    ->find();
                $spec_info = D('Cart')->get_spec_price($spec_info, $this->_user_id);
                $mix_list['Goods'][$key]['price'] = $spec_info['price'];
                $mix_items[] = $mix_list['Goods'][$key];
                if (!array_key_exists($val['cate_id'], $mix_cates)) {
                    $cate_name_array = explode("\t", $val['cate_name']);
                    if ($cate_name_array) {
                        $cate_name = end($cate_name_array);
                        $mix_cates[$val['cate_id']] = $cate_name;
                    }
                }
            }
            unset($mix_list['Goods']);
            $mix_info = $mix_list;
            $data['mix_cates'] = $mix_cates;
            $data['mix_list'] = $mix_items;
            $data['mix_info'] = $mix_info;
        }
        //商品属性
        $goods_pvs = M('GoodsPvs')->where('goods_id=' . $id)->find(); // 取出该商品的属性字符串
        $goods_pvs_str = $goods_pvs['pvs'];
        $props = array();
        if (!empty($goods_pvs_str)) {
            $goods_pvs_arr = explode(';', $goods_pvs_str); //  分割成数组
            foreach ($goods_pvs_arr as $pv) {
                if ($pv) {
                    $pv_arr = explode(':', $pv);
                    $prop = M('GoodsProp')->where('pid=' . $pv_arr[0] . ' AND status=1')->find();
                    if ($prop) {
                        $prop_value = M('GoodsPropValue')->where('pid=' . $pv_arr[0] . ' AND vid=' . $pv_arr[1] . ' AND status=1')->find();
                        if ($prop_value) {
                            $props[] = array('name' => $prop['name'], 'value' => $prop_value['prop_value']);
                        }
                    }
                }
            }
        }
//      lichen 2019/5/21 start
        //商品上层规格分类
        $spec = array();
        $_spec = array();
        if ($goods['_specs'] && is_array($goods['_specs'])) {
//            if ($goods['spec_qty'] > 0 && $goods['_specs'] && is_array($goods['_specs'])) {

                foreach ($goods['_specs'] as $k => $v) {

                    if ($v['spec_1'] && $v['spec_1value']) {
                        $spec['spec_1']['k'] = $goods['spec_name_1'];
                        if(!in_array($v['spec_1value'],$spec['spec_1']['v']) && !in_array($v['spec_1'],$spec['spec_1']['c'])){
                            $spec['spec_1']['v'][] = $v['spec_1value'];
                            $spec['spec_1']['c'][] = $v['spec_1'];
                        }
                    }

                    if ($v['spec_2']) {
                        $spec['spec_2']['k'] = $goods['spec_name_2'];
                        if(!in_array($v['spec_2'],$spec['spec_2']['v'])) {
                            $spec['spec_2']['v'][] = $v['spec_2'];
                        }
                    }
                    if ($v['spec_3']) {
                        $spec['spec_3']['k'] = $goods['spec_name_3'];
                        if(!in_array($v['spec_3'],$spec['spec_3']['v'])) {
                            $spec['spec_3']['v'][] = $v['spec_3'];
                        }
                    }
                    if ($v['spec_4']) {
                        $spec['spec_4']['k'] = $goods['spec_name_4'];
                        if(!in_array($v['spec_4'],$spec['spec_4']['v'])) {
                            $spec['spec_4']['v'][] = $v['spec_4'];
                        }
                    }


                }
            $_spec = array_values($spec);

            $data['goods']['_spec'] = $_spec;

            foreach ($data['goods']['_specs'] as $k => $v){
                $temp = $data['goods']['_specs'][$k]['spec_1'];
                $data['goods']['_specs'][$k]['spec_1'] = $data['goods']['_specs'][$k]['spec_1value'];
                $data['goods']['_specs'][$k]['spec_1value'] = $temp;
            }

            //删除库存为0的规格
            foreach ($goods['_specs'] as $key => $value) {
                if ($value['stock'] < 0 && $value['stock'] == 0) {
                    unset($goods['_specs'][$key]);
                }
            }
            $data['goods']['tax_description'] = C('TAX_DESCRIPTION');
//      lichen 2019/5/21 end
            $data['goods']['props'] = $props;
            if(!$goods['spec_qty'] > 0 || !$goods['_specs'] || !is_array($goods['_specs'])){
                $data['goods']['_specs'][0]['spec_1value'] = $data['goods']['default_image'];
             }
        }
        render('10000', '成功', $data);

    }

        /**
         * @api {get} /index.php?m=Home&c=Goods&a=detail 显示商品的详情信息
         *
         * @apiName 显示商品的详情信息
         * @apiGroup All
         * @apiVersion 0.1.0
         * @apiDescription 显示商品的详情信息
         *
         *
         *
         */
        function detail()
        {
            $id = I('request.id');
            if (empty($id)) {
                render('10001', '缺少参数');
            }

            /* 商品信息 */
            $goods = D('goods')->get_info($id);
            if (!$goods || $goods['if_show'] == 0 || $goods['closed'] == 1 || $goods['state'] != 1) {
                render('10300', '此商品不存在');
            }
            $goods['description'] = str_replace("./data", C('SITE_URL') . '/data', $goods['description']);
            $this->assign('goods', $goods);
            $this->display();
        }


        function lefttime($time)
        {
            $lefttime = $time - time();
            if (empty($time) || $lefttime <= 0) {
                return array();
            }
            $d = intval($lefttime / 86400);
            $lefttime -= $d * 86400;
            $h = intval($lefttime / 3600);
            $lefttime -= $h * 3600;
            $m = intval($lefttime / 60);
            $lefttime -= $m * 60;
            $s = $lefttime;
            return array(
                "d" => $d,
                "h" => $h,
                "m" => $m,
                "s" => $s
            );
        }

        /**
         * @api {get} /index.php?m=Home&c=Goods&a=comments 获取产品的评价
         */
        function comments()
        {
            $goods_id = I('request.id');
            if (empty($goods_id)) {
                render('10001', '缺少参数');
            }
            import("Org.Com.Evaluation");
            $evaluation = new \Org\Com\Evaluation;

            $data = array();

            $conditions = "goods_id = '$goods_id' AND evaluation_status = '1'";
            if (in_array(I('request.evalscore'), array('1', '2', '3'))) {
                $conditions .= ' AND evaluation=' . $_GET['evalscore'];
            }
            if (I('request.havecomment') == '1') {
                $conditions .= ' AND comment !=""';
            }

            $comments = M('OrderGoods')->alias('ordergoods')
                ->field('buyer_id, buyer_name, anonymous, evaluation_time, comment, evaluation')
                ->where($conditions)->join('LEFT JOIN ' . C('DB_PREFIX') . 'order order_alias ON order_alias.order_id=ordergoods.order_id')
                ->page(I('request.page', 1, 'intval') . ',10')
                ->order('evaluation_time desc')
                ->select();

            //获取买家的信誉
            if (!empty($comments)) {
                foreach ($comments as $key => $value) {
                    $data = $evaluation->get_buyer_evaluation($value['buyer_id']);
                    $comments[$key]['buyer_credit_value'] = $data['buyer_credit_value'];
                    $comments[$key]['buyer_credit_image'] = $data['buyer_credit_image'];
                    $comments[$key]['buyer_praise_rate'] = $data['buyer_praise_rate'];
                    $comments[$key]['evaluation_time'] = date('Y-m-d H:i:s', $value['evaluation_time']);
                }
            }
            unset($data['buyer_credit_value']);
            unset($data['buyer_credit_image']);
            unset($data['buyer_praise_rate']);
            $data['comments'] = $comments;
            render('10000', '', $data);
        }


}
